<?php

namespace app\models\user;

use Yii;

/**
 * This is the model class for table "user_refill".
 *
 * @property int $id
 * @property string $sn
 * @property int $user_id
 * @property float $amount
 * @property int $status 0未支付 1已支付
 * @property string $create_time
 * @property string $update_time
 */
class UserRefill extends \yii\db\ActiveRecord
{
    /**
     * status list
     * @var int[]
     */
    public static $statusMapping = [
        'ALL'       => -1,
        'OK'        => 1,
        'NOT'     => 0,
    ];

    /**
     * status display list
     * @var int[]
     */
    public static $statusMappingDisplay = [
        '全部'       => -1,
        '已支付'       => 1,
        '已取消'       => 0,
    ];

    /**
     * Status list
     *
     * @return array
     */
    public static function statusList()
    {
        $list = [];
        foreach (self::$statusMappingDisplay as $key => $value) {
            $list[] = [
                'label' => $key,
                'value' => $value
            ];
        }

        return $list;
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_refill';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['sn'], 'required'],
            [['user_id', 'status'], 'integer'],
            [['amount'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['sn'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sn' => 'Sn',
            'user_id' => 'User ID',
            'amount' => 'Amount',
            'status' => 'Status',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public static function generateSn()
    {
        do {
            $sn = date('YmdHis') . mt_rand(10000, 99999);
        } while(self::findOne(['sn' => $sn]));

        return $sn;
    }
}
